<template>
  <div>
    <el-breadcrumb separator=">">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 Search-->
    <el-card>
      <el-form :inline="true">
        <el-form-item>
          <el-input class="search" v-model="search" placeholder="请输入内容" />
          <el-button :icon="Search" @click="query"></el-button>
        </el-form-item>
        <!-- 后面的按钮 -->
        <el-form-item>
          <el-button type="primary" @click="toAdd">添加用户</el-button>
        </el-form-item>
      </el-form>
      <!-- 表格 stripe是否显示斑马 data数组,展示的数据,border 是否有边框  -->
      <el-table stripe :data="userData" border style="width: 100%">
        <!-- width 某一列的宽,label 表格头的名字  prop 里边数对象的属性名 type="index" 是否使用序列号  -->
        <el-table-column type="index" label="#" width="50"></el-table-column>
        <el-table-column prop="username" label="姓名" width="180"></el-table-column>
        <el-table-column prop="email" label="邮箱" width="180"></el-table-column>
        <el-table-column prop="mobile" label="电话" width="180"></el-table-column>
        <el-table-column prop="role_name" label="角色" width="180"></el-table-column>
        <el-table-column label="状态" width="80">
          <template v-slot="scope">
            <el-switch
              v-model="scope.row.mg_state"
              style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="scope">
            <el-button type="primary" size="small" :icon="EditPen" @click="getUsersId(scope.row.id)" />
            <el-button type="danger" size="small" :icon="Delete" @click="delUsersId(scope.row.id)" />
            <el-button type="warning" size="small" :icon="Setting" @click="getRolesData(scope.row)" />
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页  v-model:current-page当前页数  v-model:page-size每页显示条目个数
        small是否使用小型分页样式  disabled是否禁用分页 -->
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[1, 5, 10, 15]"
        small
        :disabled="disabled"
        :background="background"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
      <!-- 添加用户 -->
      <el-dialog v-model="centerDialogVisible" title="添加用户" width="60%" draggable>
        <el-form :model="userform" :rules="ruleform" ref="uesrformRef">
          <el-form-item label="用户名" prop="username" :label-width="100">
            <el-input v-model="userform.username" autocomplete="off" placeholder="输入用户名" />
          </el-form-item>
          <el-form-item label="密码" prop="password" label-width="100px">
            <el-input v-model="userform.password" autocomplete="off" placeholder="输入密码" />
          </el-form-item>
          <el-form-item label="邮箱" prop="email" :label-width="100">
            <el-input v-model="userform.email" autocomplete="off" placeholder="输入邮箱" />
          </el-form-item>
          <el-form-item label="手机号" prop="mobile" :label-width="100">
            <el-input v-model="userform.mobile" autocomplete="off" placeholder="输入手机号" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="centerDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="addUser">确定</el-button>
          </div>
        </template>
      </el-dialog>
      <!-- 修改信息对话框 -->
      <el-dialog v-model="centerDialogVisibleUpdate" title="修改信息" width="500" draggable>
        <el-form :model="userform" ref="uesrUpdataformRef" :rules="ruleform">
          <el-form-item label="用户名" :label-width="100">
            <el-input disabled v-model="userform.username" autocomplete="off" />
          </el-form-item>
          <el-form-item label="邮箱" :label-width="100" prop="email">
            <el-input v-model="userform.email" autocomplete="off" />
          </el-form-item>
          <el-form-item label="手机号" :label-width="100" prop="mobile">
            <el-input v-model="userform.mobile" autocomplete="off" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="centerDialogVisibleUpdate = false">取消</el-button>
            <el-button type="primary" @click="updateUser">确定</el-button>
          </div>
        </template>
      </el-dialog>
      <!-- 分配角色 -->
      <el-dialog title="分配角色" v-model="centerDialogVisibleRole" width="50%">
        <el-row>
          <el-col :span="3">当前的用户:</el-col>
          <el-col :span="21">{{ useRow.username }}</el-col>
        </el-row>
        <el-row>
          <el-col :span="3">当前的角色:</el-col>
          <el-col :span="21">{{ useRow.role_name }}</el-col>
        </el-row>
        <el-row>
          <el-col :span="3">分配的角色:</el-col>
          <el-col :span="21">
            <el-select v-model="role_id" placeholder="请选择角色">
              <el-option
                :value="item.id"
                v-for="(item, index) in roleList"
                :key="index"
                :label="item.roleName"
              ></el-option>
            </el-select>
          </el-col>
        </el-row>
        <!-- 具名插槽 -->
        <span class="dialog-footer">
          <el-button @click="centerDialogVisibleRole = false">取 消</el-button>
          <el-button type="primary" @click="usersIdRole">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup lang="ts">
// 操作字体 图标
import { Delete, EditPen, Setting, Search } from '@element-plus/icons-vue'
import { onMounted, ref } from 'vue'
import request from '@/util/request'
import type { responseUserData, userp } from '@/api/user/type'
import { ElMessage, ElMessageBox } from 'element-plus'
// const userData: any[] = [
//   {
//     username: 'mazikang',
//     email: 'mazikang@qq.com',
//     mobile: '15103307610',
//     role_name: '超级管理员',
//     mg_state: true,
//   },
// ]
// 搜索框
const search = ref('')
// 列表数据
const userData = ref<userp[]>([])
// 分页
// 总条数
const total = ref(100)
// 当前页
// const currentPage = ref(1)
let currentPage = 1
// 每页查询条数
let pageSize = 5
// 是否禁用分页
const disabled = ref(false)
// 是否为分页按钮添加背景色
const background = ref(false)
// page-size 改变时触发
const handleSizeChange = (size: number) => {
  pageSize = size
  getUser()
  console.log('handleSizeChange')
}
// current-page 改变时触发
const handleCurrentChange = (current: number) => {
  currentPage = current
  getUser()
  console.log('handleCurrentChange')
}
// 获取dom元素
const uesrformRef = ref({})
// 获取修改提交时的dom元素
const uesrUpdataformRef = ref({})
// 搜索框
const query = () => {
  // 每次搜索,页数从1开始
  currentPage = 1
  getUser()
}
// 添加的数据
const getEmptyUser = () => {
  return {
    username: '',
    password: '',
    email: '',
    mobile: '',
  }
}
// 对话框数据
const userform = ref<userp>(getEmptyUser())
// 添加用户按钮
const toAdd = () => {
  centerDialogVisible.value = true
  // 每次打开数据制空
  userform.value = getEmptyUser()
}
// 对话框校验
const ruleform = {
  username: [
    // required必填项  message错误信息   triggerRef 触发条件
    { required: true, message: '请输入用户名', triggerRef: 'blur' },
  ],
  password: [{ required: true, message: '请输入密码', triggerRef: 'blur' }],
  email: [
    // pattern校验方式
    { pattern: /^\w+(?:\.[_a-zA-Z0-9]+)*@\w*qq.com$/, message: '请输入qq邮箱', triggerRef: 'blur' },
  ],
  mobile: [
    // pattern校验方式
    { required: true, message: '请输入手机号', triggerRef: 'blur' },
    { pattern: /^1[34578]\d{9}/, message: '请输入正确的手机号', triggerRef: 'blur' },
  ],
}
// 获取列表数据
const getUser = async () => {
  const { data }: responseUserData = await request({
    url: `/users?query=${search.value}&pagenum=${currentPage}&pagesize=${pageSize}`,
    method: 'GET',
    // 在请求方法中 添加请求头
    // headers: {
    //   Authorization:
    //     'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOjUwMCwicmlkIjowLCJpYXQiOjE3MTY3MjQyMzUsImV4cCI6MTcxNjgxMDYzNX0.V-HNGBr_PRUNtS--su4MJZ0k81fQ5kyTf-P3dcitPnw',
    // },
  })
  userData.value = data.users
  total.value = data.total
  console.log('11111111111111111', data)
}
onMounted(() => {
  getUser()
})
// 添加用户
const addUser = () => {
  uesrformRef.value.validate(async (valid) => {
    // 如果是false
    if (!valid) {
      return ElMessage.error('请填写正确信息')
    }
    const { meta }: responseUserData = await request({
      url: '/users',
      method: 'POST',
      data: userform.value,
    })
    console.log(meta)
    if (meta.status !== 201) {
      if (meta.status !== 400) {
        return ElMessage.error('网络异常，稍后重试')
      }
      return ElMessage.error(meta.msg)
    }
    ElMessage.success(meta.msg)
    centerDialogVisible.value = false
    getUser()
  })
}
// 添加用户对话框是否显示
let centerDialogVisible = ref(false)
// 修改对话框是否显示
let centerDialogVisibleUpdate = ref(false)
// 分配设置对话框是否显示
let centerDialogVisibleRole = ref(false)
// 分配设置一行数据
let useRow = {}
// 角色id
let role_id = ref('')
// 所有角色的信息
let roleList = ref([])
// 根据id获修改用户信息
const getUsersId = async (id: any) => {
  const { data, meta }: any = await request({
    url: `/users/${id}`,
    type: 'GET',
  })
  if (meta.status !== 200) {
    return ElMessage.error('修改数据时网络异常，稍后重试')
  }
  userform.value = data
  centerDialogVisibleUpdate.value = true
}
//修改用户提交
const updateUser = () => {
  uesrUpdataformRef.value.validate(async (valid) => {
    if (!valid) {
      return ElMessage.error('请填写正确信息')
    }
    const { meta }: responseUserData = await request({
      url: `/users/${userform.value.id}`,
      method: 'PUT',
      data: userform.value,
    })
    if (meta.status !== 200) {
      return ElMessage.error('修改数据时网络异常，稍后重试')
    }
    // 刷新页面数据
    getUser()
    centerDialogVisibleUpdate.value = false
    return ElMessage.success(meta.msg)
  })
}

// 根据id获删除用户信息
// const delUsersId = async (id: any) => {
//   const { meta }: responseUserData = await request({
//     url: `/users/${id}`,
//     method: 'DELETE',
//   })
//   if (meta.status !== 200) {
//     return ElMessage.error('删除数据时网络异常，稍后重试')
//   }
//   getUser()
//   return ElMessage.success(meta.msg)
// }
const delUsersId = async (id: any) => {
  try {
    await ElMessageBox.confirm('是否删除数据', '危险', {
      confirmButtonText: '是',
      cancelButtonText: '否',
      type: 'error',
    })
    const { meta }: responseUserData = await request({
      url: `/users/${id}`,
      method: 'DELETE',
    })
    // console.log(data,meta)
    // 获取数据失败
    if (meta.status !== 200) {
      return ElMessage.error('删除数据时网络异常，稍后重试')
    }
    // 页数>1 并数据只有一条  跳转到上一页
    if (currentPage > 1 && userData.value.length === 1) {
      currentPage = currentPage - 1
    }
    // 刷新数据
    getUser()
    return ElMessage.success(meta.msg)
  } catch (error) {
    return ElMessage.info('已经取消')
  }
}
// 分配角色
const getRolesData = async (user: any) => {
  centerDialogVisibleRole.value = true
  useRow = user
  // 获取到所有的角色
  const { data, meta }: any = await request({
    url: `/roles`,
    method: 'GET',
  })
  console.log(meta)
  roleList.value = data
}
// 分配用户的id
const usersIdRole = async () => {
  const { data, meta }: any = await request({
    url: `users/${useRow.id}/role`,
    data: { rid: role_id.value },
    method: 'PUT',
  })
  console.log(data)
  if (meta.status !== 200) {
    return ElMessage.error('网络异常 稍后重试')
  }
  // 关闭对话框
  centerDialogVisibleRole.value = false
  // 重新遍历用户信息
  getUser()
}
</script>

<style scoped>
.el-breadcrumb {
  margin-top: 10px;
}

.el-card {
  margin-top: 20px;
}

.search {
  width: 540px;
}
</style>
: any: any: {}(: any)(: any)(: any)(: any)(: any)(: any)
